﻿using AutoMapper;
using B.S.Meeting.Domain;
using B.S.Meeting.ErrorCode;
using B.S.Meeting.Infrastructure.Interfaces;
using B.S.Meeting.WriteAPI.Applications.Commands.Users;
using MD5Hash;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Yitter.IdGenerator;

namespace B.S.Meeting.WriteAPI.Applications.CommandHandlers.Users
{
    public class AddUserCommandHandler : IRequestHandler<AddUserCommand, APIResult<int>>
    {
        IBaseRepository<User> uRep;
        IMapper mapper;
        ILogger<AddUserCommandHandler> logger;

        public AddUserCommandHandler(IBaseRepository<User> uRep, ILogger<AddUserCommandHandler> logger, IMapper mapper)
        {
            this.uRep = uRep;
            this.logger = logger;
            this.mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(AddUserCommand request, CancellationToken cancellationToken)
        {
            try
            {
                User user = mapper.Map<User>(request.Data);
                user.UserPwd = request.Data.UserPwd.GetMD5();
                user.IDnumber=YitIdHelper.NextId();
                await uRep.AddAsync(request.Data);
                return new APIResult<int>
                {
                    Code=StatusEnumCode.Ok,
                    Message="添加用户信息成功",
                    Data=1
                };
            }
            catch (Exception ex)
            {
                logger.LogError("添加用户信息失败", ex.Message);
                throw;
            }
        }
    }
}
